package com.uenpay.im.ui.talklist;

import java.util.ArrayList;

import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.GroupTalkDbManager;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.MenuMsgType;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.QyxTopMsg;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.R2;
import com.uenpay.im.adapter.TalkLongClickViewAdapter;
import com.uenpay.im.adapter.TopListMsgAdapter;
import com.uenpay.im.callback.FragmentCallBack;
import com.uenpay.im.callback.IPopupWindowListener;
import com.uenpay.im.configuration.ShareData;
import com.uenpay.im.entities.PopupEntity;
import com.uenpay.im.entities.TalkLongClickViewEntity;
import com.uenpay.im.ui.contacts.ContactsActivity;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.company.CreateCompanyActivity;
import com.uenpay.im.ui.old.activity.contacts.SearchFriendsActivity;
import com.uenpay.im.ui.old.activity.group.ChooseCreateGroupTypeActivity;
import com.uenpay.im.ui.old.activity.group.SearchGroupsActivity;
import com.uenpay.im.view.MyPopupWindow;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.zxing.CaptureActivity;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 会话列表 CopyRight:http://www.qiyunxin.com
 *
 * @author SL
 * @Create Date: 2014-12-7 下午1:36:44
 */

public class TalkListFragment extends Fragment {

    private static final String TAG = "TalkListFragment";

    private FragmentCallBack mFragmentCallBack;
    private TextView conn_status;
    protected TopListMsgManager topListMsgManager = new TopListMsgManager();
    private TalkMsgManager takeMsgManager = new TalkMsgManager();
    private MsgReceiver msgReceiver = null;
    protected ArrayList<QyxTopMsg> msg_list = new ArrayList<QyxTopMsg>();
    protected ArrayList<QyxTopMsg> temp_msg_list = new ArrayList<QyxTopMsg>();
    protected TopListMsgAdapter topListMsgAdapter;
    private boolean is_query = false;
    private View view;
    private ListView msg_lv;
    private MyPopupWindow myPopupWindow;
    private GroupTalkDbManager mGroupTalkDbManager = new GroupTalkDbManager();

    @BindView(R2.id.title_textview)
    TextView tvTitle;
    @BindView(R2.id.title_right_contacts_iv)
    ImageView ivContacts;
    @BindView(R2.id.title_right_add_iv)
    ImageView ivAdd;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_talk_list_layout, container, false);
            ButterKnife.bind(this, view);
            initView();
            initLisenter();
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        return view;
    }

    private void initView() {
        conn_status = (TextView) view.findViewById(R.id.conn_status);
        msg_lv = (ListView) view.findViewById(R.id.talk_list);
        view.findViewById(R.id.back_layout).setVisibility(View.GONE);
        view.findViewById(R.id.title_right_iv_layout).setVisibility(View.VISIBLE);
        tvTitle.setText(R.string.main_msg);
        ivContacts.setImageResource(R.drawable.ic_contacts_red);
        ivAdd.setImageResource(R.drawable.ic_add_red);
        myPopupWindow = new MyPopupWindow(getActivity(), getPopData(), new IPopupWindowListener() {

            @Override
            public void itemClick(int index) {
                if (index == 1) {
                    Intent intent = new Intent(getActivity(), ChooseCreateGroupTypeActivity.class);
                    startActivity(intent);
                } else if (index == 2) {
                    Intent intent = new Intent(getActivity(), SearchFriendsActivity.class);
                    startActivity(intent);
                }/* else if (index == 3) {
                    Intent intent = new Intent(getActivity(), SearchGroupsActivity.class);
                    startActivity(intent);
                }*/ else if (index == 3) {
                    Intent intent = new Intent(getActivity(), CaptureActivity.class);
                    startActivity(intent);
                } else if (index == 4) {
//                    Intent intent = new Intent(getActivity(), CreateCompanyActivity.class);
//                    startActivity(intent);
                }
            }
        });
        view.findViewById(R.id.title_right_contacts_iv).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().startActivity(new Intent(getActivity(), ContactsActivity.class));
            }
        });
        if (topListMsgAdapter == null) {
            Log.d(TAG, "initView new TopListMsgAdapter");
            topListMsgAdapter = new TopListMsgAdapter(getActivity(), msg_list);
        }
        msg_lv.setAdapter(topListMsgAdapter);
    }

    private ArrayList<PopupEntity> getPopData() {
        ArrayList<PopupEntity> arrayList = new ArrayList<PopupEntity>();
        PopupEntity entity = new PopupEntity(R.drawable.icon_pop_chat, R.string.start_group, 1);
        PopupEntity entity1 = new PopupEntity(R.drawable.icon_pop_newfriend, R.string.add_friends, 2);
        PopupEntity entity2 = new PopupEntity(R.drawable.icon_pop_scan, R.string.sweep, 3);
        PopupEntity entity3 = new PopupEntity(R.drawable.icon_pop_money, R.string.get_money, 4);
        arrayList.add(entity);
        arrayList.add(entity1);
        arrayList.add(entity2);
        arrayList.add(entity3);
        return arrayList;
    }

    private void initLisenter() {
        view.findViewById(R.id.title_right_add_iv).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (myPopupWindow != null) {
                    myPopupWindow.show(arg0);
                }
            }
        });

        msg_lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                QyxTopMsg topMsg = (QyxTopMsg) parent.getAdapter().getItem(position);
                int count = topMsg.msg_count;

                ActivityHandle.startChat(getActivity(), topMsg.sessionModel.getSessionId(), topMsg.sessionModel.getSessionType(),
                        topMsg.sessionModel.getOperationType(), topMsg.chat_name, count, null);

                if (topMsg.msg_count != 0) {
                    topMsg.msg_count = 0;
                    topListMsgAdapter.notifyDataSetChanged();
                    UpdateTotalMsg(null);
                    topListMsgManager.update(topMsg);
                }
                /** 修改@信息 **/
                if (topMsg.is_at == 1) {
                    updateAtMsg(topMsg);
                }

            }

        });

        msg_lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                deleteDialog((QyxTopMsg) parent.getAdapter().getItem(position));
                return true;
            }
        });
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume " + IMApplication.IS_REFRESH_TOP_MSG);
        if (IMApplication.IS_REFRESH_TOP_MSG) {
            Log.d(TAG, "queryMsg");
            queryMsg(null);
        }
        if (msgReceiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(BroadcastAction.GET_TALKDETAIL_ACTION);
            filter.addAction(BroadcastAction.TAKEING_MSG_TOP_MSG);
            filter.addAction(BroadcastAction.ACTION_CONN_STAUTS);
            filter.addAction(BroadcastAction.CLEAR_TALK_MSG_ACTION);
            filter.addAction(BroadcastAction.ACTION_WITHDRAW_MSG);
            filter.addAction(BroadcastAction.ACTION_REFRESH_AVATAR);
            filter.addAction(BroadcastAction.ACTION_CLEAR_MSG_COUNT);
            filter.addAction(BroadcastAction.ACTION_REFRESH_FRIEND_NAME);
            filter.addAction(BroadcastAction.DELETE_FRIEND_ACTION);

            msgReceiver = new MsgReceiver();
            getActivity().registerReceiver(msgReceiver, filter);
        }
        ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_TALK);
        IMApplication.notification_sum = 0;
        NotificationManager mNotificationManager = (NotificationManager) IMApplication.getAppContext().getSystemService(
                Context.NOTIFICATION_SERVICE);
        mNotificationManager.cancel(0);

        super.onResume();
    }

    protected void queryMsg(final String action) {
        if (is_query) {
            return;
        }
        is_query = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                msg_list = topListMsgManager.query();
                Log.d(TAG, "queryMsg msg_list: " + msg_list.toString());
                Message msg = myHandler.obtainMessage();
                msg.what = 3;
                msg.obj = action;
                myHandler.sendMessage(msg);
            }
        }).start();

    }

    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.d(TAG, "onReceive : " + action);
            if (action.equals(BroadcastAction.TAKEING_MSG_TOP_MSG) || action.equals(BroadcastAction.ACTION_WITHDRAW_MSG)) {
                queryMsg(BroadcastAction.TAKEING_MSG_TOP_MSG);
            } else if (intent.getAction().equals(BroadcastAction.GET_TALKDETAIL_ACTION)) {
                String status = intent.getStringExtra("status");
                if (status.equals("success")) {
                    Message msg = myHandler.obtainMessage();
                    msg.obj = intent.getStringExtra("name");
                    msg.arg1 = intent.getIntExtra("chat_id", 0);
                    msg.what = 0;
                    myHandler.sendMessage(msg);
                }

            } else if (intent.getAction().equals(BroadcastAction.ACTION_CONN_STAUTS)) {
                int status_code = intent.getIntExtra("status_code", 0);
                Message msg = myHandler.obtainMessage();
                msg.arg1 = status_code;
                msg.what = 1;
                myHandler.sendMessage(msg);

            } else if (intent.getAction().equals(BroadcastAction.CLEAR_TALK_MSG_ACTION)
                    || intent.getAction().equals(BroadcastAction.DELETE_FRIEND_ACTION)) {
                Message msg = myHandler.obtainMessage();
                msg.what = 2;
                myHandler.sendMessage(msg);
            } else if (intent.getAction().equals(BroadcastAction.ACTION_CLEAR_MSG_COUNT)) {
                Message msg = myHandler.obtainMessage();
                msg.what = 2;
                myHandler.sendMessage(msg);
            } else if (intent.getAction().equals(BroadcastAction.ACTION_REFRESH_AVATAR)
                    || intent.getAction().equals(BroadcastAction.ACTION_REFRESH_FRIEND_NAME)) {
                queryMsg(null);
            }
        }
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            Log.d(TAG, "handleMessage msg what = " + msg.what + " obj = " + msg.obj + msg.arg1);
            if (msg.what == 0) {
                topListMsgManager.updateName((long) msg.arg1, msg.obj + "", PacketType.GROUP);
                for (int i = 0; i < msg_list.size(); i++) {
                    if (msg_list.get(i).from_cust_id == msg.arg1 && msg_list.get(i).sessionModel.getSessionType() == PacketType.GROUP) {
                        msg_list.get(i).chat_name = msg.obj + "";
                        break;
                    }
                }
                UpdateTotalMsg(null);
            } else if (msg.what == 1) {
                if (msg.arg1 == 200) {
                    conn_status.setVisibility(View.GONE);
                    conn_status.setText(R.string.conn_status);
                } else if (msg.arg1 == 100) {
                    conn_status.setText(R.string.recv_msg_status);
                    conn_status.setVisibility(View.VISIBLE);
                } else {
                    conn_status.setVisibility(View.VISIBLE);
                }
            } else if (msg.what == 2) {
                queryMsg(null);
            } else if (msg.what == 3) {
                if (topListMsgAdapter == null) {
                    Log.d(TAG, "new TopListMsgAdapter");
                    topListMsgAdapter = new TopListMsgAdapter(IMApplication.getAppContext(), msg_list);
                    msg_lv.setAdapter(topListMsgAdapter);
                } else {
                    topListMsgAdapter.setData(msg_list);
                }
                UpdateTotalMsg((String) msg.obj);
                is_query = false;
                IMApplication.IS_REFRESH_TOP_MSG = false;
            }
            return false;
        }
    });

    /**
     * 这里设置底部显示的总消息未读数
     */
    private void UpdateTotalMsg(String action) {
        int sum = 0;
        for (int i = 0; i < msg_list.size(); i++) {
            if (msg_list.get(i).msg_count != 0) {
                if (msg_list.get(i).sessionModel.getSessionType() == PacketType.PERSONAL) {
                    FriendEntity friendEntity = FriendDB.getFriend(msg_list.get(i).sessionModel.getSessionId() + "");
                    if (friendEntity.is_remind == 0) {
                        sum += msg_list.get(i).msg_count;
                    }
                } else {
                    GroupTalkEntity groupTalk = mGroupTalkDbManager.queryGroupByGroupId(msg_list.get(i).sessionModel.getSessionId());
                    if (groupTalk != null && groupTalk.is_remind == 0) {
                        sum += msg_list.get(i).msg_count;
                    }
                }
            }
        }
        Log.d(TAG, "传给首页的消息数量 " + sum);
        IMApplication.config.setUnreadChatMsgCount(sum);
        mFragmentCallBack.updateTabMsg(FragmentCallBack.TABTYPE.TAB_TALK_MSG, FragmentCallBack.REMINDTYPE.TAB_REMIND_NEW_MSG, sum);
    }

    private void deleteDialog(final QyxTopMsg msg) {
        TalkLongClickViewAdapter adapter = null;

        final MyDialog.Builder dlg = new MyDialog.Builder(getActivity());
        final ListView menus = new ListView(getActivity());
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        menus.setLayoutParams(params);
        adapter = new TalkLongClickViewAdapter(getActivity(), getLongClickContent(msg.msg_count));
        menus.setAdapter(adapter);

        dlg.setListView(menus);
        dlg.setMessage("");
        if (!TextUtils.isEmpty(msg.chat_name) && msg.sessionModel.getSessionType() == PacketType.PERSONAL) {
            dlg.setTitle(msg.chat_name);
        } else if (msg.sessionModel.getSessionType() == PacketType.GROUP) {
            dlg.setTitle(R.string.delete_dialog_msg_title);
        } else {
            dlg.setTitle(R.string.action_dialog_title);
        }
        dlg.create().show();
        menus.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                TalkLongClickViewEntity mTalkLongClickViewEntity = (TalkLongClickViewEntity) arg0.getAdapter().getItem(arg2);
                if (mTalkLongClickViewEntity != null) {
                    if (mTalkLongClickViewEntity.type == MenuMsgType.DELETE) {
                        new DeleteMsgTask(msg).execute();
                    } else if (mTalkLongClickViewEntity.type == MenuMsgType.MARK_READ) {
                        setMarkReadMsg(msg);
                    } else if (mTalkLongClickViewEntity.type == MenuMsgType.MARK_UNREAD) {
                        setMarkUnReadMsg(msg);
                    }
                }
                dlg.getDialog().dismiss();
            }
        });

    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mFragmentCallBack = (FragmentCallBack) activity;
    }

    @Override
    public void onPause() {
        super.onPause();
        ShareData.getInstance().setCurPage(IMApplication.PAGE.PAGE_NULL);
    }

    @Override
    public void onDestroy() {
        if (msgReceiver != null) {
            getActivity().unregisterReceiver(msgReceiver);
        }
        super.onDestroy();
    }

    /**
     * 删除消息
     *
     * @author SL
     */
    private class DeleteMsgTask extends AsyncTask<Void, Void, Void> {
        private QyxTopMsg delMsg = null;

        public DeleteMsgTask(QyxTopMsg _DelMsg) {
            delMsg = _DelMsg;
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if (delMsg != null) {
                topListMsgManager.deleteByMsg(delMsg.sessionModel.getSessionId(), delMsg.sessionModel.getSessionType());
                if (delMsg.sessionModel.getSessionType() == PacketType.GROUP) {
                    takeMsgManager.deleteGroupAllMsgByGroupId(delMsg.sessionModel.getSessionId());
                } else if (delMsg.sessionModel.getSessionType() == PacketType.PERSONAL) {
                    takeMsgManager.deleteMsgByFromCustIdAndToCustId(delMsg.sessionModel.getSessionId(),
                            Long.valueOf(IMApplication.getCustId()));
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            msg_list.remove(delMsg);
            topListMsgAdapter.notifyDataSetChanged();
            UpdateTotalMsg(null);
        }
    }

    /**
     * @param count
     * @return
     */
    private ArrayList<TalkLongClickViewEntity> getLongClickContent(int count) {
        ArrayList<TalkLongClickViewEntity> arrayList = new ArrayList<TalkLongClickViewEntity>();
        TalkLongClickViewEntity mTalkLongClickViewEntity = new TalkLongClickViewEntity(MenuMsgType.DELETE, R.string.delete_talk);
        if (count > 0) {
            TalkLongClickViewEntity mTalkLongClickViewEntity1 = new TalkLongClickViewEntity(MenuMsgType.MARK_READ, R.string.mark_read);
            arrayList.add(mTalkLongClickViewEntity1);
        } else {
            TalkLongClickViewEntity mTalkLongClickViewEntity1 = new TalkLongClickViewEntity(MenuMsgType.MARK_UNREAD, R.string.mark_unread);
            arrayList.add(mTalkLongClickViewEntity1);
        }
        arrayList.add(mTalkLongClickViewEntity);

        return arrayList;
    }

    /**
     * 设置消息已读
     *
     * @param message
     */
    private void setMarkReadMsg(QyxTopMsg message) {
        int row = topListMsgManager.updateTopMsgByField(message.sessionModel.getSessionId(), message.sessionModel.getSessionType(),
                DBTopMsgColumns.MSG_COUNT, "0");
        if (row > 0) {
            message.msg_count = 0;
            refreshMsgList(message);
        }
    }

    /**
     * 设置消息未读
     *
     * @param message
     */
    private void setMarkUnReadMsg(QyxTopMsg message) {
        int row = topListMsgManager.updateTopMsgByField(message.sessionModel.getSessionId(), message.sessionModel.getSessionType(),
                DBTopMsgColumns.MSG_COUNT, "1");
        if (row > 0) {
            message.msg_count = 1;
            refreshMsgList(message);
        }
    }

    private void refreshMsgList(QyxTopMsg message) {
        for (int i = 0, size = msg_list.size(); i < size; i++) {
            if (msg_list.get(i).msg_no.equals(message.msg_no)) {
                msg_list.get(i).msg_count = message.msg_count;
                break;
            }
        }

        if (topListMsgAdapter != null) {
            topListMsgAdapter.setData(msg_list);
            topListMsgAdapter.notifyDataSetChanged();
        }
        UpdateTotalMsg(null);
    }

    /**
     * 修改@状态
     *
     * @param topMsg
     */
    private void updateAtMsg(QyxTopMsg topMsg) {
        topListMsgManager.updateTopMsgByField(topMsg.sessionModel.getSessionId(), topMsg.sessionModel.getSessionType(),
                DBTopMsgColumns.IS_AT, 0 + "");
        for (int i = 0, size = msg_list.size(); i < size; i++) {
            if (msg_list.get(i).msg_no.equals(topMsg.msg_no)) {
                msg_list.get(i).is_at = 0;
                break;
            }
        }
        topListMsgAdapter.notifyDataSetChanged();
    }

}
